package com.ynet.middleground.oss.oauth.base;

import javax.sql.DataSource;

import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;

import com.google.common.base.Throwables;
import com.ynet.core.log.IfpLogger;

/**
 * @author liulx
 * @desciprtion token 处理
 * @create 2020-10-12 13:30:42
 */
public class JdbcTokenStores extends JdbcTokenStore {

    public JdbcTokenStores(DataSource dataSource) {
        super(dataSource);
    }

    @Override
    public OAuth2AccessToken readAccessToken(String tokenValue) {
        OAuth2AccessToken accessToken = null;

        try {
            accessToken = new DefaultOAuth2AccessToken(tokenValue);
        } catch (EmptyResultDataAccessException e) {
            IfpLogger.error(Thread.currentThread().getStackTrace()[1].getMethodName(),
                "Failed to find access token for token " + tokenValue + ", case: {}",
                Throwables.getStackTraceAsString(e));
        } catch (IllegalArgumentException e) {
            IfpLogger.warn(Thread.currentThread().getStackTrace()[1].getMethodName(),
                "Failed to deserialize access token for " + tokenValue + ", case {}", e);
            removeAccessToken(tokenValue);
        }
        return accessToken;
    }

}
